package server;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import javax.imageio.ImageIO;


public class ImageReader2 {

	public static void main(String[] args)throws Exception{
		
//		读入512*512图片矩阵
		String FileName = "e:/N20031223G062731.img";
		int width  = 512;
		int height = 512;
		int total = 512*512;
		String filePath = "e:/051.jpg";

//		读入512*512图片矩阵
		RandomAccessFile rFile = new RandomAccessFile(FileName, "r");
		long point = rFile.length() - 512*512*2;
		int[] sample = new int[total];
		int si = 0;
		rFile.seek(point);
		while (rFile.getFilePointer() < rFile.length()) {
		   sample[si]= ( (rFile.readByte() &0xFF) + (rFile.readByte() & 0xFF)*256);
		   si++;
		}
		rFile.close();

		/*
		int[] sample = new int[total];
		for(int i = 0; i< total; i++){
		  sample[i]= ((imagebyte[i+1]& 0xFF)*256 + (imagebyte[i] & 0xFF));
		}*/

//		对图片做maks，转化为440*440图片矩阵
		int x = 261;
		int y = 257;
		int r = 220;

//		 (x,y):圆心坐标;  r: 半径; img：512*512图像
//		在matlab中,坐标从(1,1)开始，故此处(x,y)都减1
		x-=1;
		y-=1;
		int[] mask2 = new int[4*r*r];
		int x0 = 0;
		int y0 = 0;
				
		int tem = 0;
		y0 = y-r; 		
		int l = 2*r ; //直径
//		阈值转换
		int noise = 564;
		float k = 1.0909f;

		for(int i = 0; i< l; i++){			
				y0++;
				x0 = x-r;
				for(int j= 0; j< l; j++){
					x0++;
					tem = sample[y0*512+x0];
					if((Math.pow(x0-x,2)+ Math.pow(y0-y,2))>=Math.pow(r,2))
						mask2[i*l + j] = 0;
					else{
		                               tem -= noise;
			                       if(tem<0)  tem=0;
			                       tem = (int)((tem*k*256)/4000);	
		                               //samplefloat[i] = tem;
		                               mask2[i*l + j] = tem;
			}
		}
		}

		width = height = l;		

		BufferedImage new_img = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
		WritableRaster raster = new_img.getRaster();
		raster.setSamples(0, 0, width, height,0, mask2);

		try {
			ImageIO.write(new_img, "jpg", new File(filePath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
